package com.curd.mp.base.rest;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.curd.common.config.exception.CloudException;
import com.curd.common.config.result.Result;
import com.curd.mp.base.service.IBaseService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;


@Slf4j
public class IBaseController<DOMAIN, ID,  S extends IBaseService<DOMAIN, ID>>  {
    /**
     * 动态 IOC代理
     *
     * 多个需要使用Autowired
     */
    @Autowired
    protected S service;


    /**
     * 当前泛型真实类型的Class
     */
    private Class<DOMAIN> modelClass;

    public IBaseController() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<DOMAIN>) pt.getActualTypeArguments()[0];
    }

    /**
     * 效验用户权限
     * @param userCheckId
     * @param msg
     */
    protected void checkUser(ID userCheckId,  String msg){
        service.checkUser(userCheckId, msg);
    }

    @ApiOperation(value = "分页列表")
    @RequestMapping(value = "super_page_list", method = {RequestMethod.GET})
    public Result<?> superPageList(HttpServletRequest req, HttpServletResponse res, Page page) {
        IPage<DOMAIN> entitys = service.page(page);
        Assert.notNull(entitys, "内容为空");
        return Result.ok(entitys);
    }

    /**
     *
     * @param req
     * @param res
     * @param userCheckId   用户效验ID （测试阶段可不是使用）
     * @param file
     * @return
     */
    @ApiOperation(value = "Excel批量导入")
    @RequestMapping(value = "importExcel", method = {RequestMethod.POST})
    public Result<?> importExcel(HttpServletRequest req, HttpServletResponse res, ID userCheckId, MultipartFile file) {
        checkUser(userCheckId, "请登录后重试");
        return Result.ok(service.importExcel(modelClass, file));
    }

    @ApiOperation(value = "新增/更新")
    @RequestMapping(value = "super_edit", method = RequestMethod.POST)
    public Result<?> superEdit(HttpServletRequest req, HttpServletResponse res, ID userCheckId, DOMAIN entity) {
        checkUser(userCheckId, "请登录后重试");
        return Result.ok(service.saveOrUpdate(entity));
    }

    @ApiOperation(value = "全部列表")
    @RequestMapping(value = "super_list", method = RequestMethod.GET)
    public Result<?> superList(HttpServletRequest req, HttpServletResponse res) {
        List<DOMAIN> entitys = service.list();
        Assert.notNull(entitys, "内容为空");
        return Result.ok(entitys);
    }

    @ApiOperation(value = "根据ID删除/全部删除")
    @RequestMapping(value = "super_delete", method = RequestMethod.DELETE)
    public Result<?> superDeleteByIds(HttpServletRequest req, HttpServletResponse res,
                                      ID userCheckId, ID []ids,
                                      @RequestParam(defaultValue = "false", required = false) boolean allRemove) {
        checkUser(userCheckId, "请登录后重试");
        String msg = "共删除：";
        if (allRemove){
            return Result.ok(msg + service.removeAll());
        }
        if (ids.length == 1){
            this.superGetById(req, res, ids[0]);
            return Result.ok(msg + service.removeById((Serializable) ids[0]));
        }
        return Result.ok(msg + service.removeByIds(Collections.singleton(ids)));
    }



    @ApiOperation(value = "根据ID获取")
    @RequestMapping(value = "super_get/{id}", method = RequestMethod.GET)
    public Result<?> superGetById(HttpServletRequest req, HttpServletResponse res, @PathVariable("id") ID id) {
        DOMAIN entity = service.getById((Serializable) id);
        Assert.notNull(entity, "该内容已被删除");
        return Result.ok(entity);
    }
}
